//
//  EFBFavoriteViewController.m
//  Pods
//
//  Created by E.F.B on 15-5-11.
//
//

#import "EFBFavoriteViewController.h"
#import "EFBFavoritesView.h"
#import "TCAirportModel.h"

#define EFBFavoriteArray  @[ @"黄页", @"REF", @"STR", @"APP", @"TXI", @"SID", @"CO", @"细则"]//, @"AR"

@interface EFBFavoriteViewController ()

@property (retain, nonatomic) NSMutableDictionary *favoriteDic;
@property (copy  , nonatomic) NSString *favoriteAirport;

@property (retain, nonatomic) UIButton *leftButton;
@property (retain, nonatomic) UIButton *rightButton;
@property (copy  , nonatomic) NSString *currentType;

@property (assign, nonatomic) int currentIndex;

@end

@implementation EFBFavoriteViewController

- (void)dealloc
{
    [_favoriteAirport release];
    [_currentType release];
    [_favoriteDic release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _favoriteDic = [[NSMutableDictionary alloc] init];
        _currentIndex = -1;
        
        NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(favoriteNotification:) name:@"EFBFavoriteNotification" object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ToolbarBG-Portrait"]];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"divider-top@2x"]]autorelease];
    imageView.frame = CGRectMake(0, 0, self.view.frame.size.width, 1);
    imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:imageView];
    
    self.leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.leftButton.frame = CGRectMake(0, CGRectGetHeight(self.view.frame)-35, 50, 35);
    [self.leftButton setTitle:@"上一张" forState:UIControlStateNormal];
    self.leftButton.titleLabel.font = [UIFont systemFontOfSize:12.0f];
//    [self.leftButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 30)];
    [self.leftButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.leftButton.autoresizingMask = UIViewContentModeBottomRight;
    [self.leftButton addTarget:self action:@selector(leftButtonTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.leftButton];
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightButton.frame = CGRectMake(CGRectGetWidth(self.view.frame)-50, CGRectGetHeight(self.view.frame)-35, 50, 35);
    [self.rightButton setTitle:@"下一张" forState:UIControlStateNormal];
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:12.0f];
//    [self.rightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 30, 0, 10)];
    [self.rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.rightButton.autoresizingMask = UIViewContentModeBottomLeft;
    [self.rightButton addTarget:self action:@selector(rightButtonTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.rightButton];
}

- (void)getFavoriteCount:(NSString *)airport
{
    NSMutableDictionary *countDic = [NSMutableDictionary dictionary];
    NSDictionary *favorateDic = [[TCAirportModel getFavorateDic] objectForKey:airport];
    NSArray *array = [favorateDic allKeys];
    for (NSString *s in array) {
        NSArray *tmpArray = [favorateDic objectForKey:s];
        [countDic setObject:[NSNumber numberWithInt:[tmpArray count]] forKey:s];
    }
    
    [self createFavoriteView:countDic];
}

- (void)_addFavoritesToView
{
    int tmp_width = 0;
    int tmp_x = 0;
    
    for (EFBFavoritesView *v in [self.favoriteDic allValues]) {
        
        CGSize size = [v.spacePageControl sizeForNumberOfPages:v.PageCount];
        int size1 = size.width > 50 ? size.width : 50;
        tmp_width += size1 + 15;
    }
    
    tmp_x = (self.view.frame.size.width - tmp_width)/2;
    
    for (NSString *string in EFBFavoriteArray) {
        EFBFavoritesView *vc = (EFBFavoritesView *)[self.favoriteDic objectForKey:string];
        if (vc) {
            CGSize size = [vc.spacePageControl sizeForNumberOfPages:vc.PageCount];
            int size1 = size.width > 50 ? size.width : 50;
            
            CGRect rect = CGRectMake(tmp_x, 0, size1, 40);
            vc.frame = rect;
            
            tmp_x += (size1 + 15);
        }
    }
    [self.view bringSubviewToFront:self.leftButton];
    [self.view bringSubviewToFront:self.rightButton];
}

- (void)favoriteNotification:(NSNotification *)notification
{
    NSString *type = [notification.userInfo objectForKey:@"type"];
//    if (![self.currentType isEqualToString:type]) {
//        self.currentType = type;
//    }
    EFBFavoritesView *view = (EFBFavoritesView *)[self.favoriteDic objectForKey:type];
    if (!view) {
        view = [[[EFBFavoritesView alloc] init] autorelease];
        view.frame = CGRectZero;
        view.typeLabel.text = type;
        view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [self.view addSubview:view];
        [self.favoriteDic setObject:view forKey:type];
    }
    
    [view updatePageDisplay:[notification.userInfo objectForKey:@"favorate"]];
    
    for (NSString *s in [self.favoriteDic allKeys]) {
        
        EFBFavoritesView * v = (EFBFavoritesView *)[self.favoriteDic objectForKey:s];
        CGSize size = [v.spacePageControl sizeForNumberOfPages:v.PageCount];
        if (size.width == 0) {
            [self.favoriteDic removeObjectForKey:s];
            [v removeFromSuperview];
        }
    }
    
    [self _addFavoritesToView];
    
    NSString *airport = [notification.userInfo objectForKey:@"airport"];
    NSDictionary *openDic = notification.object;
    NSDictionary *favorateDic = [[TCAirportModel getFavorateDic] objectForKey:airport];
    NSDictionary *selectedDic = [[TCAirportModel getSelectedDic] objectForKey:[NSString stringWithFormat:@"%@%@",airport,type]];

    NSArray *array = [favorateDic objectForKey:type];

    if ([openDic isEqual:selectedDic]) {
        int tmp = 0;
        for (int i = 0; i < [array count]; i ++) {
            NSDictionary *dic = [array objectAtIndex:i];
            if ([dic isEqual:selectedDic]) {
                [self reloadFavoriteViewWithType:type index:i];
                break;
            }
            tmp ++;
            if (tmp == [array count]) {
                [self reloadFavoriteViewWithType:@"-" index:-1];
            }
        }
    }else{
        if ([self.currentType isEqualToString:type] && self.currentIndex >= [array count]) {
            [self reloadFavoriteViewWithType:type index:self.currentIndex -1 ];
        }
    }
}

- (void)createFavoriteView:(NSMutableDictionary *)dic
{
    for (NSString *s in [dic allKeys]) {
        EFBFavoritesView *view = (EFBFavoritesView *)[self.favoriteDic objectForKey:s];
        if (!view) {
            view = [[[EFBFavoritesView alloc] init]autorelease];
            view.frame = CGRectZero;
            view.typeLabel.text = s;
            [view reloadCountView:[dic objectForKey:s]];
            view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
            [self.view addSubview:view];
            [self.favoriteDic setObject:view forKey:s];
        }
    }
    
    [self _addFavoritesToView];
}

- (void)displayPageControl:(NSString *)airport
{
    _favoriteAirport = [airport copy];

    for (NSString *s in [self.favoriteDic allKeys]) {
        
        EFBFavoritesView * v = (EFBFavoritesView *)[self.favoriteDic objectForKey:s];
        [v removeFromSuperview];
        [self.favoriteDic removeObjectForKey:s];
    }

    self.currentType = nil;
    self.currentIndex = -1;
    
    [self getFavoriteCount:airport];
}

- (void)viewDidLayoutSubviews
{
    if (self.favoriteAirport) {
        [self _addFavoritesToView];
//        [self displayPageControl:self.favoriteAirport];
//        [self reloadFavoriteViewWithType:self.currentType index:self.currentIndex];
    }
}

- (void)leftButtonTap
{
    @autoreleasepool {
        
        if (!self.currentType) {
            return;
        }
        int passIndex = _currentIndex;
        EFBFavoritesView *view = (EFBFavoritesView *)[self.favoriteDic objectForKey:self.currentType];
        
        if (passIndex -1 >= 0) { //view.spacePageControl.currentPage
            view.typeLabel.textColor = [UIColor blackColor];
            _currentIndex --;
            view.spacePageControl.currentPage = _currentIndex;
            [view.spacePageControl updateCurrentPageDisplay];
        }else{
            
            int cycleCount = 0;
            NSInteger index = -1;
            for (int i = [EFBFavoriteArray count]-1; i >= 0; i --) {
                NSString *string = [EFBFavoriteArray objectAtIndex:i];
                if ([string isEqualToString:self.currentType]) {
                    index = [EFBFavoriteArray indexOfObject:self.currentType];
                }
                if (index > 0) {
                    NSString *tmpType = [EFBFavoriteArray objectAtIndex:--index];
                    EFBFavoritesView *view1 = (EFBFavoritesView *)[self.favoriteDic objectForKey:tmpType];
                    if (view1) {
                        _currentIndex = -1;
                        view.spacePageControl.currentPage = _currentIndex;
                        [view.spacePageControl updateCurrentPageDisplay];
                        view.typeLabel.textColor = [UIColor lightGrayColor];
                        
                        view1.typeLabel.textColor = [UIColor blackColor];
                        _currentIndex = view1.spacePageControl.numberOfPages-1;
                        view1.spacePageControl.currentPage = _currentIndex;
                        [view1.spacePageControl updateCurrentPageDisplay];
                        
                        self.currentType = tmpType;
                        break;
                    }
                }
                cycleCount ++;
                if (cycleCount == [EFBFavoriteArray count]) {
                    return;
                }
            }
        }
        if (_delegate && (passIndex != _currentIndex || passIndex == 0 )) {
            if ([_delegate respondsToSelector:@selector(nextOrPreviousChartClickedWithType:index:)]) {
                [self.delegate nextOrPreviousChartClickedWithType:self.currentType index:_currentIndex];
            }
        }
    }
}

- (void)rightButtonTap
{
    @autoreleasepool {
        
        if (!self.currentType) {
            for (NSString *string in EFBFavoriteArray) {
                EFBFavoritesView *view = (EFBFavoritesView *)[self.favoriteDic objectForKey:string];
                if (view) {
                    self.currentType = string;
                    break;
                }
            }
        }
        int passIndex = _currentIndex;
        
        EFBFavoritesView *view = (EFBFavoritesView *)[self.favoriteDic objectForKey:self.currentType];
        
        if (view.spacePageControl.numberOfPages > _currentIndex+1) {
            view.typeLabel.textColor = [UIColor blackColor];
            _currentIndex ++;
            view.spacePageControl.currentPage = _currentIndex;
            [view.spacePageControl updateCurrentPageDisplay];
        }else{
            int cycleCount = 0;
            NSInteger index = -1;
            for (NSString *string in EFBFavoriteArray) {
                if ([string isEqualToString:self.currentType]) {
                    index = [EFBFavoriteArray indexOfObject:self.currentType];
                }
                if (index< [EFBFavoriteArray count]-1) {
                    NSString *tmpType = [EFBFavoriteArray objectAtIndex:++index];
                    EFBFavoritesView *view1 = (EFBFavoritesView *)[self.favoriteDic objectForKey:tmpType];
                    if (view1) {
                        _currentIndex = -1;
                        view.spacePageControl.currentPage = _currentIndex;
                        [view.spacePageControl updateCurrentPageDisplay];
                        view.typeLabel.textColor = [UIColor lightGrayColor];
                        
                        _currentIndex ++;
                        view1.typeLabel.textColor = [UIColor blackColor];
                        view1.spacePageControl.currentPage = _currentIndex;
                        [view1.spacePageControl updateCurrentPageDisplay];
                        
                        self.currentType = tmpType;
                        break;
                    }
                }
                cycleCount ++;
                if (cycleCount == [EFBFavoriteArray count]) {
                    return;
                }
            }
        }
        
        if (_delegate && (passIndex != _currentIndex || passIndex == 0)) {
            if ([_delegate respondsToSelector:@selector(nextOrPreviousChartClickedWithType:index:)]) {
            [self.delegate nextOrPreviousChartClickedWithType:self.currentType index:_currentIndex];
            }
        }
    }
}

- (void)reloadFavoriteViewWithType:(NSString *)type index:(int)index
{
    if (([type isEqualToString:@""] || [type isEqualToString:@"-"]) && index == -1) {
        EFBFavoritesView *view = (EFBFavoritesView *)[self.favoriteDic objectForKey:self.currentType];
        if (view) {
            view.spacePageControl.currentPage = -1;
            [view.spacePageControl updateCurrentPageDisplay];
            view.typeLabel.textColor = [UIColor lightGrayColor];
//            if ([type isEqualToString:@"-"]) {
//                self.currentIndex --;
//            }
        }
        return;
    }
    if (self.currentType) {
        EFBFavoritesView *view = (EFBFavoritesView *)[self.favoriteDic objectForKey:self.currentType];
        if (view) {
            view.spacePageControl.currentPage = -1;
            [view.spacePageControl updateCurrentPageDisplay];
            view.typeLabel.textColor = [UIColor lightGrayColor];
        }
    }
    
    self.currentType = type;
    self.currentIndex = index;
    
    EFBFavoritesView *view1 = (EFBFavoritesView *)[self.favoriteDic objectForKey:self.currentType];
    if (view1) {
        view1.typeLabel.textColor = [UIColor blackColor];
        view1.spacePageControl.currentPage = index;
        [view1.spacePageControl updateCurrentPageDisplay];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
